﻿using Mapster;
using Minotaur.App.Core;
using Minotaur.App.Core.Mvvm;
using Minotaur.App.Core.Redis;
using Minotaur.App.Domains.Model.Menu;
using Minotaur.App.Domains.Request;
using Minotaur.App.Domains.ViewModel;
using Minotaur.App.Domains.ViewModel.Table;
using Minotaur.App.Modules.Business.Service.Table;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json;
using Prism.Commands;
using Prism.Mvvm;
using Prism.Regions;
using ServiceStack;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using Minotaur.App.Modules.SystemControl.Views;
using Minotaur.App.Domains.Model.Table;
using Minotaur.App.Domains.Model.Resouces;
using HandyControl.Controls;
using Minotaur.App.Core.Attributes;

namespace Minotaur.App.Modules.SystemSet.ViewModels
{
    public class TableViewModel : WindowComputeViewModel
    {
        private readonly ITableService tableService;

        public TableViewModel(IRegionManager regionManager, IDbContext dbContext, IRedisClient _redisClient, ITableService _tableService) : base(regionManager, dbContext, _redisClient)
        {
            this.tableService = _tableService;
        }


        #region 属性注册区域 

        private ObservableCollection<TableInfoListViewModel> tableInfoListViewModels = new ObservableCollection<TableInfoListViewModel>();

        /// <summary>
        /// 数据表列表信息
        /// </summary>
        public ObservableCollection<TableInfoListViewModel> TableInfoListViewModels { get => tableInfoListViewModels; set => SetProperty(ref tableInfoListViewModels, value); }
        #endregion

        #region 注册函数区域

        #region 命令注册
        /// <summary>
        /// 新增
        /// </summary>
        public ICommand AddCommand => new DelegateCommand<object>(AddAction);

        /// <summary>
        /// 搜索方法
        /// </summary>
        public ICommand SearchCommand => new DelegateCommand(SearchAction);

        private void SearchAction()
        {
            InitTables();
        }


        /// <summary>
        /// 新增
        /// </summary>
        /// <param name="obj"></param>
        /// <exception cref="NotImplementedException"></exception>
        private void AddAction(object obj)
        {
        }

        /// <summary>
        /// 启用禁用
        /// </summary>
        /// <param name="obj"></param>
        /// <exception cref="NotImplementedException"></exception>
        [GlobalLogAspect]
        private void EnableOrDisabledAction(object obj)
        {
            OpendLoading = true;
            Task.Run(async () =>
            {
                var results = true;
                TableInfoListViewModel viewModel = (TableInfoListViewModel)obj;
                bool status = viewModel.Enable.HasValue ? !viewModel.Enable.Value : false;
                var dbResult = await this.dbContext.BusinessDb.UseSugarTranAsync(async () =>
                {
                    await this.dbContext.BusinessDb.Updateable<TableInfo>()
                    .SetColumns(o => o.Enable == status)
                    .Where(o => o.Autoid == viewModel.Autoid)
                    .ExecuteCommandAsync();
                    return true;
                });
                results = dbResult.IsSuccess;
                if (results)
                {
                    this.ShowSuccess = status ? "启用成功！" : "禁用成功！";
                    InitTables();
                    this.Dispatcher.Invoke(delegate
                    {
                        this.IsRightDrawerOpen = false; 
                    });
                }
                else
                {
                    this.Dispatcher.Invoke(delegate
                    {
                        this.IsRightDrawerOpen = false;
                        OpendLoading = false;
                        Growl.Error("禁用失败!");
                    });
                }
            });
        }

        /// <summary>
        /// 编辑
        /// </summary>
        /// <param name="obj"></param>
        /// <exception cref="NotImplementedException"></exception>
        private void EditAction(object obj)
        {
        }

        /// <summary>
        /// 字段管理
        /// </summary>
        /// <param name="obj"></param>
        /// <exception cref="NotImplementedException"></exception>
        private void FieldsManagerAction(object obj)
        {
            RegionManager?.RequestNavigate(RegionNames.ContentRegion, "fieldmanager");
        }

        #endregion 

        private SystemControl.Views.Pagination pagination;

        public override void InitData()
        {
            pagination = this.ListPagination as SystemControl.Views.Pagination;
            pagination.ViewModel.PageEventClick += PageEventClick;
            InitTables();
            //thvorow new NotImplementedException();
        }

        private void InitTables()
        { 
            Task.Run(async () =>
            {
                SearcheRequest request = SearchViewModel.Adapt<SearcheRequest>();
                TableInfoListRespone tableInfo = await this.tableService.IniTableInfos(request);
                Dispatcher.Invoke(() =>
                {
                    try
                    {
                        if (tableInfo is null) return;
                        this.TableInfoListViewModels = tableInfo.List.Adapt<ObservableCollection<TableInfoListViewModel>>();
                        foreach (var item in TableInfoListViewModels)
                        {
                            item.EditAction = this.EditAction;
                            item.EnableOrDisabledAction = this.EnableOrDisabledAction;
                            item.DeleteAction = this.DeleteAction;
                            item.FieldsManagerAction = this.FieldsManagerAction;
                            item.CreatorName = GetEmpCache(item.Creator.ToInt());
                        }
                        pagination.ViewModel.Total = tableInfo.TotalCount;
                        OpendLoading = false;
                    }
                    catch (Exception ex)
                    {
                        throw ex;
                    }
                });
            });
        }
        [GlobalLogAspect]
        private void DeleteAction(object obj)
        {
            OpendLoading = true;
            Task.Run(async () =>
            {
                var results = true;
                TableInfoListViewModel viewModel = (TableInfoListViewModel)obj;
                var dbResult = await this.dbContext.BusinessDb.UseSugarTranAsync(async () =>
                {
                    await this.dbContext.BusinessDb.Updateable<TableInfo>()
                    .SetColumns(o => o.HaveDelete == true)
                    .Where(o => o.Autoid == viewModel.Autoid)
                    .ExecuteCommandAsync();
                    return true;
                });
                results = dbResult.IsSuccess;
                if (results)
                {
                    this.ShowSuccess = "删除数据表信息成功!";
                    InitTables(); 
                }
                else
                {
                    this.Dispatcher.Invoke(delegate
                    {
                        OpendLoading = false;
                        Growl.Error("删除数据表信息失败!");
                    });
                }
            });
        }

        private void PageEventClick(object sender, RoutedEventArgs e)
        {
            SearchViewModel searchViewModel = (SearchViewModel)e.OriginalSource;
            this.SearchViewModel.PageIndex = searchViewModel.PageIndex;
            this.SearchViewModel.PageSize = searchViewModel.PageSize;
            this.InitTables();
        }

        #endregion
    }
}
